package com.zhentao.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.common.constants.WemediaConstants;
import com.zhentao.common.constants.WmNewsMessageConstants;
import com.zhentao.mapper.WmMaterialMapper;
import com.zhentao.mapper.WmNewsMapper;
import com.zhentao.mapper.WmNewsMaterialMapper;
import com.zhentao.mapper.WmUserMapper;
import com.zhentao.model.common.dtos.PageResponseResult;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.enums.AppHttpCodeEnum;
import com.zhentao.model.wemedia.dto.NewsAuthDto;
import com.zhentao.model.wemedia.dto.WmNewsDto;
import com.zhentao.model.wemedia.dto.WmNewsPageReqDto;
import com.zhentao.model.wemedia.pojo.WmMaterial;
import com.zhentao.model.wemedia.pojo.WmNews;
import com.zhentao.model.wemedia.pojo.WmNewsMaterial;
import com.zhentao.model.wemedia.pojo.WmUser;
import com.zhentao.model.wemedia.vo.WmNewsVo;
import com.zhentao.service.WmNewsAutoScanService;
import com.zhentao.service.WmNewsService;
import com.zhentao.service.WmNewsTaskService;
import com.zhentao.utils.WmUserThreadLocalUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

import static com.baomidou.mybatisplus.core.toolkit.Wrappers.update;

@Service
public class WmNewsServiceImpl implements WmNewsService {
    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;
    @Autowired
    private WmNewsTaskService wmNewsTaskService;
    @Autowired
    private WmUserMapper wmUserMapper;
    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //检查参数
        dto.checkParam();
        //分页查询
        IPage iPage = new Page(dto.getPage(), dto.getSize());

        QueryWrapper<WmNews> queryWrapper = new QueryWrapper<>();
        //查看userId
        queryWrapper.lambda().eq(WmNews::getUserId, WmUserThreadLocalUtil.getUser().getId());
        //分频道查看
        queryWrapper.lambda().eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId());
        //查看状态
        queryWrapper.lambda().eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus());
        //根据关键字查询
        queryWrapper.lambda().like(dto.getKeyword() != null, WmNews::getLabels, dto.getKeyword());
        //时间范围区间查询
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {
            queryWrapper.lambda().between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }
        //进行分页
        iPage = wmNewsMapper.selectPage(iPage, queryWrapper);
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), Integer.valueOf(iPage.getTotal() + ""));
        responseResult.setCode(200);
        responseResult.setErrorMessage("请求成功");
        responseResult.setData(iPage.getRecords());
        return responseResult;
    }

    @Override
    public ResponseResult submitNews(WmNewsDto dto) {
        //检查查询参数为空，返回无效参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //把参数封装一下
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        //补全属性
        wmNews.setUserId(WmUserThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setEnable((short) 1);
        //提交时间
        if (dto.getStatus() == 1) {
            wmNews.setSubmitedTime(new Date());

        }
        //获取文章的封面
        if (dto.getImages() != null && dto.getImages().size() > 0) {
            //前端传一个或多个图片
            String images = StringUtils.join(dto.getImages(), ",");
            wmNews.setImages(images);
        }
        //处理tinyint 不能是负数  -1---->4
        if (dto.getType() == WemediaConstants.WM_NEWS_TYPE_AUTO) {
            dto.setType((short) 4);//0无图，1单图，2多图
            wmNews.setType(((short) 4));
        }
        //添加数据库
        //判断是新增还是修改
        if (dto.getId() == null) {
            //新增
            wmNewsMapper.insert(wmNews);
        } else {
            //修改，首先删除素材与内容/封面的关系
            //删除关联关系
            Integer newsId = dto.getId();
            QueryWrapper<WmNewsMaterial> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(WmNewsMaterial::getNewsId, newsId);
            wmNewsMaterialMapper.delete(queryWrapper);
            //删除之后执行修改
            wmNewsMapper.updateById(wmNews);
            //新增关联
            //处理封面 封面是自己上传的 /封面是自动获取的
            if (dto.getType() != 4) {
                List<String> images = dto.getImages();
                //把url转换成id
                List<Integer> mids = new ArrayList<>();
                for (String image : images) {
                    QueryWrapper<WmMaterial> materialQueryWrapper = new QueryWrapper<>();
                    materialQueryWrapper.lambda().eq(WmMaterial::getUrl, image);
                    WmMaterial wmMaterial = wmMaterialMapper.selectOne(materialQueryWrapper);
                    mids.add(wmMaterial.getId());
                }
                //把关系维护进去
                wmNewsMaterialMapper.saveRelations((short) 1, wmNews.getId(), mids);
            } else {
                //自动获取封面，一般是第一个
                List<String> images = new ArrayList<>();
                List<Map> maps = JSON.parseArray(dto.getContent(), Map.class);
                for (Map map : maps) {
                    //图片
                    if (map.get("type").equals("image")) {
                        //把获取到的图片保存到images中
                        images.add((String) map.get("value"));
                    }
                }
                //没有图片
                if (images.size() == 0) {
                    //没有图片的话type为0
                    WmNews wmNews1 = new WmNews();
                    wmNews1.setId(wmNews.getId());
                    wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
                    wmNewsMapper.updateById(wmNews1);
                } else {
                    if (images.size() == 1) {
                        //修改type=1
                        WmNews wmNews1 = new WmNews();
                        wmNews1.setId(wmNews.getId());
                        wmNews1.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                        //
                        String newsImages = StringUtils.join(images, ",");
                        wmNews1.setImages(newsImages);
                        wmNewsMapper.updateById(wmNews1);
                        List<Integer> mids = new ArrayList<>();
                        for (String image : images) {
                            //处理素材与news
                            QueryWrapper<WmMaterial> mateQ = new QueryWrapper<>();
                            mateQ.lambda().eq(WmMaterial::getUrl, image);
                            WmMaterial wmMaterial = wmMaterialMapper.selectOne(mateQ);
                            mids.add(wmMaterial.getId());
                        }
                        //把关系维护
                        wmNewsMaterialMapper.saveRelations((short) 1, wmNews.getId(), mids);
                    }
                }
            }
        }

//        处理内容与素材直接的关系   从里面把素材获取到url  --  id  添加操作
//        如果状态是0  草稿    状态是1--》待审核【自动审核   人工审核】
        if (dto.getStatus() == 1) {
//            调用了自动审核的方法。
//            wmNewsAutoScanService.autoScanWnMews(wmNews.getId());
            //先添加到任务里面再去执行
            wmNewsTaskService.addNewsToTask(wmNews.getId(), wmNews.getPublishTime());
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 文章上下架
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //1.检查参数
        if (dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.查询文章
        WmNews wmNews = wmNewsMapper.selectById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }

        //3.判断文章是否已发布
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "当前文章不是发布状态，不能上下架");
        }

        //4.修改文章enable
        wmNews.setEnable(dto.getEnable());
        wmNewsMapper.updateById(wmNews);

        if (wmNews.getArticleId() != null) {
            Map<String, Object> map = new HashMap<>();
            map.put("articleId", wmNews.getArticleId());
            map.put("enable", dto.getEnable());

            //发送消息到kafka
            kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC, JSON.toJSONString(map));
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }

    /**
     * 查询文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(NewsAuthDto dto) {
        //1.参数检查
        dto.checkParam();

        //记录当前页
        int currentPage = dto.getPage();

        //2.分页查询+count查询
        dto.setPage((dto.getPage() - 1) * dto.getSize());
        List<WmNewsVo> wmNewsVoList = wmNewsMapper.findListAndPage(dto);
        int count = wmNewsMapper.findListCount(dto);

        //3.结果返回
        ResponseResult responseResult = new PageResponseResult(currentPage, dto.getSize(), count);
        responseResult.setData(wmNewsVoList);
        return responseResult;
    }

    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        //1.检查参数
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章信息
        WmNews wmNews = wmNewsMapper.selectById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //3.查询用户信息
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());

        //4.封装vo返回
        WmNewsVo vo = new WmNewsVo();
        //属性拷贝
        BeanUtils.copyProperties(wmNews, vo);
        if (wmUser != null) {
            vo.setAuthorName(wmUser.getName());
        }

        ResponseResult responseResult = new ResponseResult().ok(vo);

        return responseResult;
    }

    /**
     * 审核文章状态，4成功 2失败
     *
     * @param status
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDto dto) {
        //1.检查参数
        if (dto == null || dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章信息
        WmNews wmNews = wmNewsMapper.selectById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //3.修改文章的状态
        wmNews.setStatus(status);
        if (org.apache.commons.lang3.StringUtils.isNotBlank(dto.getMsg())) {
            wmNews.setReason(dto.getMsg());
        }
        wmNewsMapper.updateById(wmNews);

        //审核成功，则需要创建app端文章数据，并修改自媒体文章
        if (status.equals(WemediaConstants.WM_NEWS_AUTH_PASS)) {
            //创建app端文章数据
            ResponseResult responseResult = wmNewsAutoScanService.saveAppArticle(wmNews);
            if (responseResult.getCode().equals(200)) {
                wmNews.setArticleId((Long) responseResult.getData());
                wmNews.setStatus(WmNews.Status.PUBLISHED.getCode());
                wmNewsMapper.updateById(wmNews);
            }
        }

        //4.返回
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
